package com.streaminggbs.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.streaminggbs.common.base.VideoReturnBean;
import com.streaminggbs.common.constant.AlarmAnalysisEnum;
import com.streaminggbs.common.constant.AlarmMethodEnum;
import com.streaminggbs.common.constants.Constants;
import com.streaminggbs.common.job.StreamCheckJob;
import com.streaminggbs.common.utils.RedisUtil;
import com.streaminggbs.entity.*;
import com.streaminggbs.interfaces.*;
import com.streaminggbs.model.DownloadAllRecordModel;
import com.streaminggbs.model.DownloadProgressModel;
import com.streaminggbs.model.DownloadQueryRecordModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class Gb28181ServiceImpl implements Gb28181Service{

    @Autowired
    private SysParamSetService sysParamSetService;

    @Autowired
    private DeviceAlarmService deviceAlarmService;
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private DeviceChannelInfoService deviceChannelInfoService;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 2.20 实时音视频请求从web发起(0x100F)主要针对国标设备
     */
    @Override
    public String play(String device, String channel, int vedioType, Integer record, boolean isPlan, JSONObject jsonObject) {
        String url = null;
        try {
            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
            if(vedioType==0) {//视频
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                JSONObject param = new JSONObject();
                param.put("channel", channel);
                param.put("device", device);
                HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
                ResponseEntity<JSONObject> responseEntity =restTemplate.postForEntity(deviceVideoServiceUrl+Constants.LIVE_PLAY, formEntity,JSONObject.class);
                JSONObject jsonObjectBody = responseEntity.getBody();
                if (null != jsonObject&& jsonObjectBody!=null) {
                    jsonObject.putAll(jsonObjectBody);
                }
            }
            return url;
        } catch (Exception e) {
            log.error("{}", "GB28181音视频传输请求协议下发JSON格式数据包编码异常", e);
            return url;
        }
    }

    /**
     * 2.21 实时音视频控制从web发起(0x1010)主要针对国标设备
     */
    @Override
    public void playControl(String device, String channel, int command, int closeType, int switchType, boolean isPlan) {
        try {
            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            JSONObject param = new JSONObject();
            param.put("channel", channel);
            param.put("device", device);
            HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
            ResponseEntity<JSONObject> responseEntity =restTemplate.postForEntity(deviceVideoServiceUrl+Constants.LIVE_STOP, formEntity,JSONObject.class);
            log.info("关闭播放的返回值:{}",JSONObject.toJSONString(responseEntity.getBody()));
        } catch (Exception e) {
            log.error("", e);
        }
    }


    @Override
    public JSONArray queryVedioList(String device, String channel, Integer memoryType, String startTime, String endTime) {
        JSONArray jsonArray = new JSONArray();
        try {
            if (memoryType == null) {
                memoryType = 0;
            }
            if (memoryType == 2) {
                try {
                    JSONArray jsonArray1 = findRecord(device, channel, 0, startTime, endTime);
                    if (jsonArray1 != null && jsonArray1.size() > 0) {
                        jsonArray.addAll(jsonArray1);
                    }
                } catch (Exception e) {
                    log.error("", e);
                }
                try {
                    JSONArray jsonArray2 = findRecord(device, channel, 1, startTime, endTime);
                    if (jsonArray2 != null && jsonArray2.size() > 0) {
                        jsonArray.addAll(jsonArray2);
                    }
                } catch (Exception e) {
                    log.error("", e);
                }
            } else {
                jsonArray = findRecord(device, channel, memoryType, startTime, endTime);
            }
        }catch (Exception e){
            log.error("",e);
        }
        return jsonArray;
    }
    public JSONArray findRecord(String device, String channel, int memoryType, String startTime, String endTime){
        JSONArray jsonArray = new JSONArray();
        JSONObject object =  queryVedioList3(device, channel, memoryType, startTime, endTime);
        if(object!=null) {
            try {
                JSONArray jsonArrayRecord = object.getJSONArray("RecordList");
                if (jsonArrayRecord != null && jsonArrayRecord.size() > 0) {
                    for (int i = 0; i < jsonArrayRecord.size(); i++) {
                        try {
                            JSONObject item = jsonArrayRecord.getJSONObject(i);

                            String startTimeBack = item.getString("StartTime");
                            if (StringUtils.isNotEmpty(startTimeBack)) {
                                startTimeBack = startTimeBack.replace("T", " ").replace("Z", "");
                            }
                            item.put("storageType", memoryType);
                            item.put("startTime", startTimeBack);
                            String endTimeBack = item.getString("EndTime");
                            if (StringUtils.isNotEmpty(startTimeBack)) {
                                endTimeBack = endTimeBack.replace("T", " ").replace("Z", "");
                            }
                            item.put("endTime", endTimeBack);
                            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
                            String url = item.getString("DownloadUrl");
                            if(StringUtils.isNotEmpty(url) && !url.startsWith("http")){
                                url = deviceVideoServiceUrl+ url;
                            }
                            item.put("DownloadUrl",url);
                        } catch (Exception e) {
                            log.error("", e);
                        }
                    }
                    jsonArray = jsonArrayRecord;
                }
            } catch (Exception e) {
                log.error("",e);
            }
        }
        return jsonArray;
    }
    public JSONObject queryVedioList3(String device, String channel, int memoryType, String startTime, String endTime) {
        try {
            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            JSONObject param = new JSONObject();
            param.put("device",device);
            param.put("channel",channel);
            param.put("starttime", startTime.replace(" ", "T"));
            param.put("endtime", endTime.replace(" ", "T"));
//            param.put("download",true);
            if(memoryType==1){
                param.put("storage","platform");
            }
            HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(deviceVideoServiceUrl+Constants.VOD_QUERY, formEntity, JSONObject.class);
            if(responseEntity!=null &&responseEntity.getBody()!=null){
                return responseEntity.getBody();
            }

        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }


    @Override
    public JSONObject playBack(String device, String channel, String startTime, String endTime) {
        JSONObject jsonReturn = new JSONObject();
        try {
            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();

            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            JSONObject param = new JSONObject();
            param.put("device", device);
            param.put("channel", channel);
            param.put("starttime", startTime.replace(" ", "T"));
            param.put("endtime", endTime.replace(" ", "T"));
            HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
            ResponseEntity<JSONObject> responseEntity =restTemplate.postForEntity(deviceVideoServiceUrl+Constants.VOD_START, formEntity,JSONObject.class);
            if (null != jsonReturn && responseEntity.getBody()!=null) {
                jsonReturn.putAll(responseEntity.getBody());
            }
            return jsonReturn;
        } catch (Exception e) {
            log.error("{}", "回放请求异常", e);
            return jsonReturn;
        }
    }

    @Override
    public VideoReturnBean deviceReboot(String device) {
        VideoReturnBean videoServerReturnBean = new VideoReturnBean();
        try {
            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            JSONObject param = new JSONObject();
            param.put("device", device);
            HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
            ResponseEntity<JSONObject> responseEntity =restTemplate.postForEntity(deviceVideoServiceUrl+Constants.DEVICE_REBOOT, formEntity,JSONObject.class);
            if (null != responseEntity && responseEntity.getBody()!=null) {

                videoServerReturnBean = responseEntity.getBody().toJavaObject(VideoReturnBean.class);;
            }
            return videoServerReturnBean;
        } catch (Exception e) {
            log.error("{}", "设备重启异常", e);

        }
        return videoServerReturnBean;
    }


    @Override
    public VideoReturnBean alarmResetguard(String device,String channel) {
        VideoReturnBean videoServerReturnBean = new VideoReturnBean();
        try {
            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            JSONObject param = new JSONObject();
            param.put("device", device);
            param.put("channel", channel);
            HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
            ResponseEntity<JSONObject> responseEntity =restTemplate.postForEntity(deviceVideoServiceUrl+Constants.alarmResetguard, formEntity,JSONObject.class);
            if (null != responseEntity && responseEntity.getBody()!=null) {

                videoServerReturnBean = responseEntity.getBody().toJavaObject(VideoReturnBean.class);;
            }
            return videoServerReturnBean;
        } catch (Exception e) {
            log.error("{}", "设备重启异常", e);
            return videoServerReturnBean;
        }
    }
    @Override
    public VideoReturnBean alarmSetguard(String device,String channel) {
        VideoReturnBean videoServerReturnBean = new VideoReturnBean();
        try {
            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            JSONObject param = new JSONObject();
            param.put("device", device);
            param.put("channel", channel);
            HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
            ResponseEntity<JSONObject> responseEntity =restTemplate.postForEntity(deviceVideoServiceUrl+Constants.alarmSetguard, formEntity,JSONObject.class);
            if (null != responseEntity && responseEntity.getBody()!=null) {

                videoServerReturnBean = responseEntity.getBody().toJavaObject(VideoReturnBean.class);;
            }
            return videoServerReturnBean;
        } catch (Exception e) {
            log.error("{}", "设备重启异常", e);
            return videoServerReturnBean;
        }
    }
    @Override
    public VideoReturnBean alarmReset(String device,String channel) {
        VideoReturnBean videoServerReturnBean = new VideoReturnBean();
        try {
            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            JSONObject param = new JSONObject();
            param.put("device", device);
            param.put("channel", channel);
            HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
            ResponseEntity<JSONObject> responseEntity =restTemplate.postForEntity(deviceVideoServiceUrl+Constants.alarmSetguard, formEntity,JSONObject.class);
            if (null != responseEntity && responseEntity.getBody()!=null) {

                videoServerReturnBean = responseEntity.getBody().toJavaObject(VideoReturnBean.class);;
            }
            return videoServerReturnBean;
        } catch (Exception e) {
            log.error("{}", "设备重启异常", e);
            return videoServerReturnBean;
        }
    }
    @Override
    public void playBackControl(String streamid,String command,Integer range,Double scale) {
        try {
            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
            JSONObject requestParam = new JSONObject();
            switch (command) {
                case "stop":
                    requestParam.put("streamid", streamid);
                    JSONObject vodStopJsonObject = postForEntity(requestParam,deviceVideoServiceUrl+Constants.VOD_STOP);
                    log.info("设备回调关闭结果:"+vodStopJsonObject.toJSONString());
                    break;
                default:
                    requestParam.put("streamid", streamid);
                    requestParam.put("command", command);
                    if(range!=null) {
                        requestParam.put("range", range);
                    }
                    if(scale!=null) {
                        requestParam.put("scale", scale);
                    }
                    JSONObject vodControlJsonObject = postForEntity(requestParam,deviceVideoServiceUrl+Constants.VOD_CONTROL);
                    log.info("调用控制指令"+command+"的返回结果:"+vodControlJsonObject.toJSONString());
                    break;
            }
        } catch (Exception e) {
            log.error("", e);
        }
    }

    /**
     * 全局post请求调用
     * @param param
     * @param requestUrl
     * @return
     */
    public ResponseEntity<JSONObject> postForResponces (JSONObject param,String requestUrl) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
        ResponseEntity<JSONObject> responseEntity =restTemplate.postForEntity(requestUrl, formEntity,JSONObject.class);
        return responseEntity;
    }

    /**
     * 直接获取返回结果值
     * @param param
     * @param requestUrl
     * @return
     */
    public JSONObject postForEntity (JSONObject param,String requestUrl) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
        ResponseEntity<JSONObject> responseEntity =restTemplate.postForEntity(requestUrl, formEntity,JSONObject.class);
        return responseEntity.getBody();
    }

    /**
     * 设备报警信息上报 (0x9019) GB28101
     *
     * @param protocol
     * @param message
     * @return
     */
    @Override
    public boolean uploadAlarm(JSONObject jSONObject) {
        try {
            AlarmInfo alarmInfo = new AlarmInfo();
            AlarmAnalysisEnum alarmAnalysisEnum = AlarmAnalysisEnum.getAlarmAnalysis(jSONObject.getIntValue("AlarmType"));
            if (null != alarmAnalysisEnum) {
                alarmInfo.setAlarmtype(alarmAnalysisEnum.getAlarmType());
                alarmInfo.setDescription(alarmAnalysisEnum.getDesc());
            }
            AlarmMethodEnum alarmMethodEnum = AlarmMethodEnum.getAlarmMethodByCode(jSONObject.getIntValue("AlarmType"));
            if (null != alarmMethodEnum) {
                alarmInfo.setAlarmmethod(alarmMethodEnum.getMethodType());
            }
            alarmInfo.setChannel(jSONObject.getString("channel"));
            alarmInfo.setTime(jSONObject.getString("AlarmTime").replace("T", " "));
            alarmInfo.setLevel(jSONObject.getIntValue("AlarmPriority"));
            alarmInfo.setLat(jSONObject.getString("Latitude"));
            alarmInfo.setLon(jSONObject.getString("Longitude"));
            deviceAlarmService.save(alarmInfo);
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 云台控制
     */
    @Override
    public boolean yuntab(String device, String channel, int zoom, int horizontal, int vertical, int zoom_level, int horizontal_level, int vertica_level, int focus) {
        try {
            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
            String command = Constants.PTZ_CONTROL_STOP;
            if (horizontal == 1 && vertical == 1) {
                command = Constants.PTZ_CONTROL_UPLEFT;
            } else if(horizontal == 1 && vertical == 2){
                command = Constants.PTZ_CONTROL_DOWNLEFT;
            } else if (vertical == 1 && horizontal == 2) {
                command = Constants.PTZ_CONTROL_UPRIGHT;
            } else if (vertical == 2 && horizontal == 2) {
                command = Constants.PTZ_CONTROL_DOWNRIGHT;
            } else if (horizontal == 1) {
                command = Constants.PTZ_CONTROL_LEFT;
            } else if (horizontal == 2) {
                command = Constants.PTZ_CONTROL_RIGHT;
            } else if (vertical == 1) {
                command = Constants.PTZ_CONTROL_UP;
            } else if (vertical == 2) {
                command = Constants.PTZ_CONTROL_DOWN;
            }else if (zoom == 1) {
                command = Constants.PTZ_ZOOM_IN;
            }else if (zoom == 2) {
                command = Constants.PTZ_ZOOM_OUT;
            }else if (focus == 1) {
                command = Constants.PTZ_FOCUS_FAR;
            }else if (focus == 2) {
                command = Constants.PTZ_FOCUS_NEAR;
            }
            if (StringUtils.isNotEmpty(command)) {
                JSONObject requestParam = new JSONObject();
                requestParam.put("device", device);
                requestParam.put("channel", channel);
                requestParam.put("command",command);
                log.info("设备请求参数:{}",requestParam.toJSONString());
                postForEntity(requestParam,deviceVideoServiceUrl+Constants.PTZ_CONTROL);
            }
//            log.info("{}", obj.toJSONString());
            return true;
        } catch (Exception e) {
            log.error("{}", "云台控制请求异常", e);
            return false;
        }
    }


    /**
     * http修改上线
     * @param jsonObject
     * @return
     */
    @Override
    public boolean httpOnLine(JSONObject jsonObject) {
        try {
            String id = jsonObject.getString("id");//后续去掉
            log.info("{}",  id + "设备上线");
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setDevice(id);
            deviceInfo = deviceInfoService.selectByOther(deviceInfo);
            if (deviceInfo == null){
                return false;
            }
            deviceInfo.setStatus(1);
            deviceInfoService.updateNotNull(deviceInfo);
            JSONObject redisJson0 = new JSONObject();
            redisJson0.put("status", 1);
            redisJson0.put("time", System.currentTimeMillis() / 1000);
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 设备离线逻辑
     * @param jsonObject
     * @return
     */
    @Override
    public boolean httpoffLine(JSONObject jsonObject) {
        try {
            String id = jsonObject.getString("id");//后续去掉
            log.info("{}", id + "设备注销");
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setDevice(id);
            deviceInfo = deviceInfoService.selectByOther(deviceInfo);
            deviceInfo.setId(deviceInfo.getId());
            deviceInfo.setStatus(0);
            deviceInfoService.updateNotNull(deviceInfo);
            JSONObject redisJson0 = new JSONObject();
            redisJson0.put("status", 0);
            redisJson0.put("time", System.currentTimeMillis() / 1000);
            try {
                Example example = new Example(DeviceChannelInfo.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("deviceid", deviceInfo.getId());
                List<DeviceChannelInfo> allChannel = deviceChannelInfoService.selectByExample(example);
                if (null != allChannel) {
                    for (DeviceChannelInfo item : allChannel) {
                        try {
                            String device = deviceInfo.getDevice();
                            JSONObject redisJson = new JSONObject();
                            redisJson.put("status", 0);
                            long time = System.currentTimeMillis() / 1000;
                            redisJson.put("time", time);
                            DeviceChannelInfo deviceChannelInfo = new DeviceChannelInfo();
                            deviceChannelInfo.setId(item.getId());
                            deviceChannelInfo.setStatus(0);
                            deviceChannelInfoService.updateNotNull(deviceChannelInfo);
                        } catch (Exception e) {
                            log.error("", e);
                        }
                    }
                }
            } catch (Exception e) {
                log.error("", e);
            }
            //入库，推送到前端
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 远程添加设备
     * @param entity
     */
    @Override
    public int addDevice(DeviceInfo entity) {
        try {
            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
            JSONObject param = new JSONObject();
            param.put("device", entity.getDevice());
            param.put("protocol", "gb28181");
            ResponseEntity<JSONObject> responseEntity = postForResponces(param,deviceVideoServiceUrl+Constants.DEVICE_ADD);
            log.info("设备添加至视频服务器返回结果:{}",responseEntity.getBody().toJSONString());
            return responseEntity.getStatusCodeValue();
        }catch (Exception e){
            log.error("",e);
        }
        return 200;//远程添加异常直接返回成功
    }

    /**
     * 远程删除设备
     * @param device
     * @return
     */
    @Override
    public int deleteDevice(String device) {
        try {
            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
            JSONObject param = new JSONObject();
            param.put("device", device);
            ResponseEntity<JSONObject> responseEntity = postForResponces(param, deviceVideoServiceUrl + Constants.DEVICE_DELETE);
            log.info("设备删除至视频服务器返回结果:{}", responseEntity.getBody().toJSONString());
            return responseEntity.getStatusCodeValue();
        }catch (Exception e){
            log.error("",e);
        }
        return 200;//远程删除异常直接返回成功
    }

    /**
     * 订阅位置信息
     * @param device
     */
    @Override
    public boolean subscribeAllLocation(String device) {
        String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
        JSONObject param = new JSONObject();
        param.put("device", device);
        ResponseEntity<JSONObject> responseEntity = postForResponces(param,deviceVideoServiceUrl+Constants.PLATFORM_DEVICE_POSITION_SUBSCRIBE);
        log.info("位置订阅返回结果:{}",responseEntity.getBody().toJSONString());
        JSONObject jsonObject = responseEntity.getBody();
        return jsonObject.getIntValue("code") == 0;
    }

    /**
     * 设备对讲开启
     * @param device
     * @return
     */
    @Override
    public JSONObject startSpeak(String device) {
        String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
        JSONObject param = new JSONObject();
        param.put("device", device);
        ResponseEntity<JSONObject> responseEntity = postForResponces(param,deviceVideoServiceUrl+Constants.PLATFORM_DEVICE_START_SPEAK);
        log.info("设备对讲返回结果:{}",responseEntity.getBody().toJSONString());
        JSONObject jsonObject = responseEntity.getBody();
        return jsonObject;
    }

    /**
     * 设备 - 下载录像TO服务器
     * @param device
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public JSONObject downloadRecord(String device, String channel, String startTime, String endTime,Integer speed) {
        // 每次下载之前都需要调用关闭的按钮再次进行下载
        String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
        // 关闭之后请求下载
        JSONObject requestDownloadParam = new JSONObject();
        requestDownloadParam.put("channel", channel);
        requestDownloadParam.put("device", device);
        requestDownloadParam.put("starttime", startTime);
        requestDownloadParam.put("endtime", endTime);
        if(speed!=null) {
            requestDownloadParam.put("speed", speed);
        }
        ResponseEntity<JSONObject> responseEntity = postForResponces(requestDownloadParam,deviceVideoServiceUrl+Constants.PLATFORM_DEVICE_DOWNLOAD_RECORD);
        log.info("下载录像TO服务器F返回结果:{}",responseEntity.getBody().toJSONString());
        JSONObject jsonObject = responseEntity.getBody();
        return jsonObject;
        //return jsonObject.toJavaObject(DownloadRecordModel.class);
    }

    /**
     * GB28181下载
     * @param device
     * @param channel
     * @param startTime
     * @param endTime
     * @param speed
     * @param seq
     * @return
     */
    @Override
    public JSONObject gb28181DownloadVideo(String device, String channel, String startTime, String endTime, Integer speed) {
        try {
            JSONObject downloadRecordModel = downloadRecord(device,channel,startTime.replace(" ", "T"),endTime.replace(" ", "T"),speed);
            return downloadRecordModel;
        } catch (Exception e) {
            log.error("{}", "回放请求异常", e);
            return null;
        }
    }

    /**
     * 获取下载的进度信息
     * @param streamId
     */
    @Override
    public DownloadProgressModel queryDownloadProgress(String streamId) {
        try {
            String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
            JSONObject param = new JSONObject();
            param.put("id", streamId);
            JSONObject responseEntity = postForEntity(param, deviceVideoServiceUrl + Constants.PLATFORM_DEVICE_DOWNLOAD_PROGRESS);
            log.info("正在获取下载的进度信息:{}", responseEntity.toJSONString());
            if(responseEntity.containsKey("data")){
                return responseEntity.getJSONObject("data").toJavaObject(DownloadProgressModel.class);
            }
        }catch (Exception e){
            log.error("",e);
        }
        return null;
    }

    /**
     * get进行调用
     * @param requestUrl
     * @return
     */
    private JSONObject getForResponces(String requestUrl) {
        ResponseEntity<JSONObject> responseEntity =restTemplate.getForEntity(requestUrl, JSONObject.class);
        return responseEntity.getBody();
    }

    /**
     * 查询下载记录信息
     * @param streamId
     * @return
     */
    @Override
    public DownloadAllRecordModel queryDownloadRecord(String streamId) {
        String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
        JSONObject param = new JSONObject();
        param.put("id", streamId);
        JSONObject responseEntity = postForEntity(param,deviceVideoServiceUrl+Constants.PLATFORM_DEVICE_DOWNLOAD_QUERY_RECORD);
        log.info("获取已经下载的记录:{},{}",streamId,responseEntity.toJSONString());
        if (responseEntity.getIntValue("code") == 200) {
            DownloadAllRecordModel downloadAllRecordModel = new DownloadAllRecordModel();
            downloadAllRecordModel.setVod(responseEntity.getJSONObject("data").getString("vod"));
            downloadAllRecordModel.setDownloadQueryRecordModels(responseEntity.getJSONObject("data").getJSONArray("list").toJavaList(DownloadQueryRecordModel.class));
            return downloadAllRecordModel;
        }
        return null;
    }

    /**
     * 设备广播
     * @param device
     * @param source
     * @param mode
     * @return
     */
    @Override
    public JSONObject broadcast(String device, String channel, String source, Integer mode) {
        String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
        JSONObject param = new JSONObject();
        param.put("channel", channel);
        param.put("device", device);
        param.put("source", source);
        param.put("mode", mode);
        ResponseEntity<JSONObject> responseEntity = postForResponces(param,deviceVideoServiceUrl+Constants.PLATFORM_DEVICE_START_BROADCAST);
        log.info("设备广播返回结果:{}",responseEntity.getBody().toJSONString());
        JSONObject jsonObject = responseEntity.getBody();
        return jsonObject;
    }

    /**
     * 取消位置订阅
     * @param device
     * @return
     */
    @Override
    public boolean cancelSubscribeAllLocation(String device) {
        String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
        JSONObject param = new JSONObject();
        param.put("device", device);
        ResponseEntity<JSONObject> responseEntity = postForResponces(param,deviceVideoServiceUrl+Constants.PLATFORM_DEVICE_CANCEL_POSITION_SUBSCRIBE);
        log.info("取消位置订阅返回结果:{}",responseEntity.getBody().toJSONString());
        JSONObject jsonObject = responseEntity.getBody();
        return jsonObject.getIntValue("code") == 0;
    }

    /**
     * 开始录像
     * @param streamid
     * @return
     */
    @Override
    public String startRealVideo (String device,String channel) {
        String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
        JSONObject param = new JSONObject();
        param.put("device", device);
        param.put("channel", channel);
        ResponseEntity<JSONObject> responseEntity = postForResponces(param,deviceVideoServiceUrl+ Constants.PLATFORM_DEVICE_START_REAL_TIME_VIDEO);
        log.info("设备正在开始实时录像:{}",responseEntity.getBody().toJSONString());
        JSONObject jsonObject = responseEntity.getBody();
        if (jsonObject.getIntValue("code") == 200) {
            return jsonObject.getString("data");
        }
        return null;
    }

    /**
     * 关闭试试录像
     * @param sinkid
     * @return
     */
    @Override
    public String stopRealVideo(String device,String channel) {
        String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
        JSONObject param = new JSONObject();
        param.put("device", device);
        param.put("channel", channel);
        ResponseEntity<JSONObject> responseEntity = postForResponces(param,deviceVideoServiceUrl+Constants.PLATFORM_DEVICE_STOP_REAL_TIME_VIDEO);
        log.info("设备正在关闭实时录像:{}",responseEntity.getBody().toJSONString());
        JSONObject jsonObject = responseEntity.getBody();
        if (jsonObject.getIntValue("code") == 200) {
            return jsonObject.getString("data");
        }
        return null;
    }

    /**
     * 获取设备在线状态
     * @param device
     * @param channel
     * @return
     */
    @Override
    public int online(String device, String channel) {
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setDevice(device);
        deviceInfo = deviceInfoService.selectByOther(deviceInfo);
        return deviceInfo.getStatus();
    }

//    @Override
//    public JSONObject stopDownload(String streamid,String gbId) {
//        String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
//        JSONObject param = new JSONObject();
//        param.put("streamid", streamid);
//        ResponseEntity<JSONObject> responseEntity = postForResponces(param,deviceVideoServiceUrl+Constants.VOD_STOP);
//        log.info("正在停止文件下载:{}",responseEntity.getBody().toJSONString());
//        JSONObject jsonObject = responseEntity.getBody();
//        log.info("停止文件下载返回结果:{}",JSONObject.toJSONString(jsonObject));
//        // 停止下载之后去掉视频的查询进度
//        //redisUtil.hdel(RedisUtil.REDIS_VIDEO_DPWNLOAD_DOMAIN,gbId);
//        return jsonObject;
//    }

    @Override
    public void stopSchedule(String device, String channel) {
        String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
        JSONObject param = new JSONObject();
		param.put("channel", channel);
        param.put("device", device);

        ResponseEntity<JSONObject> responseEntity = postForResponces(param,deviceVideoServiceUrl+Constants.PLAN_SCHEDULE_STOP);
        log.info("正在停止录像计划:{}",responseEntity.getBody().toJSONString());
        JSONObject jsonObject = responseEntity.getBody();
        log.info("正在停止录像计划返回结果:{}",JSONObject.toJSONString(jsonObject));
    }

    @Override
    public void startSchedule(String device, String channel,JSONArray times) {
        String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
        JSONObject param = new JSONObject();
        param.put("channel", channel);
        param.put("device", device);
        param.put("times", times);
        log.info("{}",param.toJSONString());
        ResponseEntity<JSONObject> responseEntity = postForResponces(param,deviceVideoServiceUrl+Constants.PLAN_SCHEDULE_START);
        log.info("正在开始录像计划:{}",responseEntity.getBody().toJSONString());
        JSONObject jsonObject = responseEntity.getBody();
        log.info("正在开始录像计划返回结果:{}",JSONObject.toJSONString(jsonObject));
    }

    @Override
    public String startPlanVideo(String device, String channel) {
        // 首先播放视频
        String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
        JSONObject param = new JSONObject();
        param.put("device", device);
        param.put("channel", channel);
        ResponseEntity<JSONObject> responseEntity =postForResponces(param,deviceVideoServiceUrl+Constants.PLATFORM_DEVICE_START_REAL_TIME_VIDEO);
        JSONObject jsonObjectBody = responseEntity.getBody();
//        if (jsonObjectBody.containsKey("code")
//                && jsonObjectBody.getIntValue("code") == 0) {
//            // 获取到视频播放流的地址
//            String streamId = jsonObjectBody.getString("StreamID");
//            // 开启实时录像
//            return startRealVideo(streamId);
//        }
        return null;
    }

    @Override
    public JSONObject getDeviceChannel(String gbId) {
        String deviceVideoServiceUrl = sysParamSetService.pick().getVideoServerUrl();
        JSONObject param = new JSONObject();
        param.put("device", gbId);
        ResponseEntity<JSONObject> responseEntity =postForResponces(param,deviceVideoServiceUrl+Constants.DEVICE_CHANNEL);
        JSONObject jsonObjectBody = responseEntity.getBody();
        return jsonObjectBody;
    }
}
